import json
import hashlib
import base64
import urllib.parse
import requests

class KDBird:
    def __init__(self):

        self.userid = 'test1587448'
        self.APIkey = '227bb3fb-a46e-4e25-bfb3-6d187339b562'

        self.DataType = '2'
        self.charset = 'utf-8'
        self.RequestType = '1002'
        self.url = 'http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json'

    def get_json_data(self, request_data):
        # json_str = {
        #     'OrderCode': '',
        #     'ShipperCode': 'ZTO',
        #     'LogisticCode': '75155304345312'
        # }
        return json.dumps(request_data)

    def get_datasign(self, request_data):

        content = self.get_json_data(request_data) + self.APIkey
        md5_str = hashlib.md5(content.encode())
        datasign = base64.urlsafe_b64encode(md5_str.hexdigest().encode())
        print(datasign)
        return datasign

    def get_form_data(self, request_data):

        form_data = urllib.parse.urlencode({
            'RequestData': self.get_json_data(request_data),
            'EBusinessID': self.userid,
            'RequestType': self.RequestType,
            'DataSign': self.get_datasign(request_data),
            'DataType': self.DataType,
        }, encoding='utf-8')
        print(form_data)
        return form_data

    def send_request(self, request_data):

        # url = 'http://sandboxapi.kdniao.com:8080/kdniaosandbox/gateway/exterfaceInvoke.json'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        }

        res = requests.post(self.url, data=self.get_form_data(request_data), headers=headers)
        print(res.content.decode())
        return res.content.decode()


kdbird = KDBird()
kdbird.url = kdbird.url
kdbird.RequestType = '1007'
request_data = {
    "OrderCode": "20190406122652000000001",
    "ShipperCode": "ZTO",
    "PayType": 1,
    "ExpType": 1,
    "CustomerName": "testzto",
    "CustomerPwd": "testztopwd",
    "Sender": {
        "Name": "Taylor",
        "Mobile": "15018442396",
        "ProvinceName": "上海",
        "CityName": "上海市",
        "ExpAreaName": "青浦区",
        "Address": "明珠路"

    },
    "Receiver": {
        "Name": "Yann",
        "Mobile": "15018442396",
        "ProvinceName": "北京",
        "CityName": "北京市",
        "ExpAreaName": "朝阳区",
        "Address": "三里屯街道"

    },
    "Commodity": [
        {"GoodsName": "鞋子"},
        {"GoodsName": "袜子"},
    ],
    "Quantity": 1
}
body_data = kdbird.send_request(request_data)
print(body_data)


